const {resolve} = require('path')
const {spawn} = require('child_process')
const rollup = require('rollup')
const {watchREQUEST} = require('../utils/watch_vite.js')
const {createRollupWatchOption, createRollupBuildOption, copyFolder} = require('../rollup')
const electron = require('electron')
let argv = process.argv.slice(2)

if (argv[0] === '--watch') {  //运行监听
  watchREQUEST({port: process.env.PORT}).then(() => {
    const watcher_options = createRollupWatchOption([
      {
        inputUrl: resolve(__dirname, '../src/main/index.js'),
        outputUrl: resolve(__dirname, '../app/main/index.js'),
        watchUrl: 'src/main/**'
      },
      {
        inputUrl: resolve(__dirname, '../src/preload/preload.js'),
        outputUrl: resolve(__dirname, '../app/preload/preload.js'),
        watchUrl: 'src/preload/preload.js'
      },
    ])
    const watcher = rollup.watch(watcher_options)
    let child = null

    watcher.on('event', e => {
      if (e.code === 'ERROR') {
        console.log(e)
      }
      if (e.code === 'END') {
        if (child) {
          child.kill()
        }
        // 更新后重新开启进程
        copyFolder(resolve(__dirname, '../src/PublicFolder'), resolve(__dirname, '../app/PublicFolder'))
        child = spawn(electron, [resolve(__dirname, '../app/main/index.js')], {
          detached: false //禁止子进程独立出父进程
        });
        child.stdout.pipe(process.stdout)
      }
    })
    watcher.on('error', function (err) {
      console.log(err)
    })
  })
} else if (argv[0] === '--build') { //打包
  createRollupBuildOption([
    {
      inputUrl: resolve(__dirname, '../src/main/index.js'),
      outputUrl: resolve(__dirname, '../app/main/index.js'),
    },
    {
      inputUrl: resolve(__dirname, '../src/preload/preload.js'),
      outputUrl: resolve(__dirname, '../app/preload/preload.js'),
    }
  ], function (bundle) {
    console.log('打包完成')
  })
}
